package com.ece.ecofitness.controller;


import java.util.HashMap;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ece.ecofitness.model.User;
import com.ece.ecofitness.service.UserService;
import com.ece.ecofitness.service.ArticleService;
import com.ece.ecofitness.service.CommandeService;


/**
 * Handles requests for the application home page.
 */
@Controller
public class ArticleController {
	
	@Autowired
	private CommandeService commandeService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private ArticleService articleService;
	
	@RequestMapping(value = "/article/get.view", method = RequestMethod.GET)
	public String getArticle(Model model,HttpServletRequest request, HttpServletResponse response) {
		String login=null;
		for(Cookie c: request.getCookies()) {
	        if(c.getName().equals("login"))
	        {
	        	login=c.getValue();
	        	break;
	        }
	    }
		if(login!=null)
		{
			model.addAttribute("article", articleService.getArticle(Integer.parseInt(request.getParameter("id"))));
			return "article";
		}
		else
			return "home";
	}
	
	@RequestMapping(value = "/article/update.view", method = RequestMethod.POST)
	public String updateArticle(Model model,HttpServletRequest request, HttpServletResponse response) {
		String login=null;
		for(Cookie c: request.getCookies()) {
	        if(c.getName().equals("login"))
	        {
	        	login=c.getValue();
	        	break;
	        }
	    }
		if(login!=null)
		{
			String label="";
		    String description="";
		    FileItem photo=null;
			int point = 0;	
			int idArticle=-1;
			try 
	        {
	        	List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	        	
	            for (FileItem item : items) {
	            	if(item.getFieldName().equals("label"))
	            		label=item.getString();
	            	else if(item.getFieldName().equals("description"))
	            		description=item.getString();
	            	else if(item.getFieldName().equals("point"))
	            		point=Integer.parseInt(item.getString());
	            	else if(item.getFieldName().equals("photo"))
	            		photo=item;
	            	else if(item.getFieldName().equals("idArticle"))
	            		idArticle=Integer.parseInt(item.getString());
	               
	            }
	            if(!articleService.updateArticle(idArticle, label, description,point,photo,request.getSession().getServletContext().getRealPath("/")))
	            	model.addAttribute("error","Updating not success!");
	            else model.addAttribute("error","Updating success!");
	            				
			} catch (FileUploadException e1) {
				model.addAttribute("error", "Erreur lors du telechargement de la photo.");	
				e1.printStackTrace();
			}
			model.addAttribute("article", articleService.getArticle(idArticle));
			return "article";
		}
		else
			return "home";
	}
	
	@RequestMapping(value = "article/add.json", method = RequestMethod.POST)
	@ResponseBody  
	public HashMap<String, Object> addArticle(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map=new HashMap<String,Object>();
		
		String login=null;
	    for(Cookie c: request.getCookies()) {
	        if(c.getName().equals("login")) login=c.getValue();
	     }
	    if(login!=null) 
	    {
	    	String label="";
		    String description="";
		    FileItem photo=null;
			int point = 0;
		    
	        try 
	        {
	        	List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	        	
	            for (FileItem item : items) {
	            	if(item.getFieldName().equals("label"))
	            		label=item.getString();
	            	else if(item.getFieldName().equals("description"))
	            		description=item.getString();
	            	else if(item.getFieldName().equals("point"))
	            		point=Integer.parseInt(item.getString());
	            	else if(item.getFieldName().equals("photo"))
	            		photo=item;
	               
	            }
	            if(articleService.addArticle(login, label, description, point,photo,request.getSession().getServletContext().getRealPath("/")))
	            	map.put("info", "Article enregistré");
		        else
		        	map.put("info", "Erreur lors de l'enregistrement de l'article.");	

			} catch (FileUploadException e1) {
				map.put("error", "Erreur lors du telechargement de la photo.");	
				e1.printStackTrace();
			}
	    }
		return map;
	}
}
